package com.pj.android.brower

import android.app.Application
import android.os.Build
import android.support.annotation.RequiresApi
import android.util.Log
import com.pj.android.brower.common.ContextManager
import com.pj.android.brower.common.GlobalService
import com.pj.android.brower.util.Config
import com.pj.android.brower.util.Constants
import com.tencent.smtt.sdk.QbSdk
import com.umeng.commonsdk.UMConfigure
import com.umeng.message.IUmengRegisterCallback
import com.umeng.message.PushAgent
import com.pj.android.brower.push.UmengNotificationService
import com.pj.android.brower.ui.WebActivity


/**
 *Create By hHui on 2018/9/27
 */
class MyApplication : Application() {
    var notifyId = 0

    companion object {
        lateinit var instance: MyApplication
        private val activaties = ArrayList<WebActivity>()

        @JvmStatic
        fun addActivity(activity: WebActivity) {
            activaties.add(activity)
        }

        @RequiresApi(Build.VERSION_CODES.N)
        @JvmStatic
        fun cleanBeforeActivity() {
            activaties.removeIf {
                if (!it.isShow) it.finish()
                !it.isShow
            }
        }
    }

    init {
        instance = this
    }

    override fun onCreate() {
        super.onCreate()
        ContextManager.setApp(applicationContext)
        GlobalService(applicationContext).start()
        initX5WebView()
        initUmengSdk()
    }

    private fun initX5WebView() { //搜集本地tbs内核信息并上报服务器，服务器返回结果决定使用哪个内核。
        QbSdk.setDownloadWithoutWifi(true)
        val cb = object : QbSdk.PreInitCallback {
            override fun onCoreInitFinished() {}

            override fun onViewInitFinished(success: Boolean) {
                Log.i("pj_log", "加载X5内核结果 $success")
            }
        }
        QbSdk.initX5Environment(applicationContext, cb)
    }

    private fun initUmengSdk() {
        UMConfigure.init(this, Constants.Umeng.appkey, "Umeng",
                UMConfigure.DEVICE_TYPE_PHONE, Constants.Umeng.messageSecret)
        //获取消息推送代理示例
        val mPushAgent = PushAgent.getInstance(this)
        mPushAgent.register(object : IUmengRegisterCallback {
            override fun onSuccess(deviceToken: String) {
                Log.i("pj_log", "初始化Umeng推送成功 deviceToken = $deviceToken")
                Config.instance.deviceToken = deviceToken
            }

            override fun onFailure(p0: String?, p1: String?) {
                Log.e("pj_log", "初始化Umeng推送失败 $p0 $p1")
            }

        })
        mPushAgent.setPushIntentServiceClass(UmengNotificationService::class.java)
    }
}